package com.lanlian.commonlib.base;

import android.content.pm.ActivityInfo;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lanlian.commonlib.BaseApplication;
import com.lanlian.commonlib.R;
import com.lanlian.commonlib.bean.RespUserLogin;
import com.lanlian.commonlib.dao.DBManager;
import com.lanlian.commonlib.event.EventCode;
import com.lanlian.commonlib.event.EventMessage;
import com.lanlian.commonlib.util.EventBusUtils;
import com.lanlian.uikit.LoadingDialog;
import com.lanlian.utillib.ToastUtils;
import com.lanlian.volleylib.HttpRequestManager;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author xiaobo.hu
 * @version v1.0
 * @date on 2018/08/03
 * @email 834366578@qq.com
 * @describe Activity基类
 */
public class BaseActivity extends AppCompatActivity {

    private LinearLayout mLayParent;
    public DBManager mDBManager;
    private LoginFinishListener mLoginFinishListener;
    public LoadingDialog mLoadingDialog;

    public TextView mTvAction;
    public ImageView mImgAction;
    public ImageView mImgBack;

    public static int activityActive;
    public static boolean isBackground;
    public static BackFrontListener mBackFrontListener;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation();
        //设置背景
        getWindow().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.color_B1)));
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mDBManager = DBManager.getInstance();
        initContentView();
    }

    protected void setRequestedOrientation() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    /**
     * 初始化contentView
     */
    private void initContentView() {
        ViewGroup viewGroup = findViewById(android.R.id.content);
        viewGroup.removeAllViews();
        mLayParent = new LinearLayout(this);
        mLayParent.setOrientation(LinearLayout.VERTICAL);
        viewGroup.addView(mLayParent);
    }

    @Override
    public void setContentView(int layoutResID) {
        LayoutInflater.from(this).inflate(layoutResID, mLayParent, true);
    }

    public void setContentView(int layoutResID, boolean isTitleNeed) {
        if (isTitleNeed) {
            LayoutInflater.from(this).inflate(R.layout.lay_title, mLayParent, true);
            mImgBack = findViewById(R.id.img_back);
            mImgBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
        setContentView(layoutResID);
    }

    /**
     * 登录之后需要需要做的
     */
    public void loginAction(RespUserLogin respLogin, LoginFinishListener loginFinishListener) {
        this.mLoginFinishListener = loginFinishListener;
        boolean success = mDBManager.saveUser(respLogin);
        if (success) {
            EventBusUtils.post(new EventMessage(EventCode.EVENT_LOGIN_REFRESH));
            EventBusUtils.post(new EventMessage(EventCode.EVENT_FUNDS_REFRESH));
            MobclickAgent.onProfileSignIn(respLogin.getUserInfo().getId().toString());
            mLoginFinishListener.onSuccess();
        } else {
            mLoginFinishListener.onFailure();
        }
    }

    public interface LoginFinishListener {
        void onSuccess();

        void onFailure();
    }

    public interface BackFrontListener {
        void onBackFront(boolean isBackground);
    }

    public ImageView getImgBack() {
        return mImgBack;
    }

    public void setTitle(String title) {
        ((TextView) findViewById(R.id.tv_title)).setText(title);
    }

    public TextView setRightStr(String str) {
        mTvAction = findViewById(R.id.tv_action);
        mTvAction.setVisibility(View.VISIBLE);
        mTvAction.setText(str);
        return mTvAction;
    }

    public void setRightColor(int color) {
        mTvAction.setTextColor(getResources().getColor(color));
    }

    public ImageView setRightImage(int id) {
        mImgAction = findViewById(R.id.img_action);
        mImgAction.setVisibility(View.VISIBLE);
        mImgAction.setImageResource(id);
        return mImgAction;
    }

    /**
     * 初始化布局
     */
    protected void initView() {
    }

    /**
     * 设置数据
     */
    protected void initData() {
    }

    /**
     * 设置监听
     */
    protected void setListeners() {
    }

    @Override
    protected void onStart() {
        activityActive++;
        if (isBackground) {
            isBackground = false;
            if (mBackFrontListener != null) {
                mBackFrontListener.onBackFront(false);
            }
            Log.e("Base", "回到前台，打开MQ");
        }
        BaseApplication.getInstance().addActivity(this);
        if (isRegisteredEventBus()) {
            EventBusUtils.register(this);
        }
        super.onStart();
    }

    @Override
    protected void onStop() {
        activityActive--;
        if (activityActive == 0) {
            isBackground = true;
            if (mBackFrontListener != null) {
                mBackFrontListener.onBackFront(true);
            }
            Log.e("Base", "进入后台，关闭MQ");
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().removeActivity(this);
        HttpRequestManager.getInstance().cancelAll(this.toString());
        if (isRegisteredEventBus()) {
            EventBusUtils.unregister(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void showLoadingDialog() {
        showLoadingDialog("加载中...");
    }

    /**
     * 显示loading对话框
     *
     * @param message 提示文字
     */
    public void showLoadingDialog(String message) {
        if (null == mLoadingDialog) {
            mLoadingDialog = new LoadingDialog(this);
        }
        mLoadingDialog.setMessage(message);
        mLoadingDialog.setCancelable(true);
        mLoadingDialog.setCanceledOnTouchOutside(false);
        try {
            mLoadingDialog.show();
        } catch (WindowManager.BadTokenException ignore) {
        }
    }

    /**
     * loading对话框显示中
     */
    public boolean isLoadingDialogShowing() {
        return mLoadingDialog != null && mLoadingDialog.isShowing();
    }

    /**
     * loading对话框消失
     */
    public void dismissLoadingDialog() {
        try {
            if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                mLoadingDialog.dismiss();
            }
            mLoadingDialog = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //取消显示loading对话框(延迟300ms关闭，避免一闪而过)
    public void dismissLoadingDialogDelayed() {
        try {
            if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                mLoadingDialog.dismissDelayed();
            }
            mLoadingDialog = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showToast(String message) {
        ToastUtils.show(this, message);
    }

    /**
     * 是否注册事件分发
     *
     * @return true 注册；false 不注册，默认不注册
     */
    protected boolean isRegisteredEventBus() {
        return false;
    }

    /**
     * 接收到分发的事件
     *
     * @param event 事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveEvent(EventMessage event) {
    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onReceiveStickyEvent(EventMessage event) {
    }

    private static final int MIN_DELAY_TIME = 2000;  // 两次点击间隔不能少于1000ms
    private long lastClickTime;

    public boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
            lastClickTime = currentClickTime;
        }
        return flag;
    }

}
